<template>
  <div class="relative w-full h-full overflow-y-auto">
    <PageHeader :title="t('menuConfig.菜单配置')" />
    <div class="menu-config-container">
      <div class="mt12 toolbar flex_aic_jcsb">
        <div class="addBtn flex_aic_jcc" @click="handleAddMenu">
          <SvgIcon name="iconxinzeng" class="mr8" />
          <span>{{ t('menuConfig.新增菜单') }}</span>
        </div>
      </div>

      <el-table
        :data="menuList"
        style="width: 100%"
        row-key="id"
        border
        v-loading="loading"
        class="cover-table"
      >
        <el-table-column
          :prop="'title' + locale"
          :label="t('menuConfig.菜单名称')"
          min-width="180"
        />
        <el-table-column :prop="'path'" :label="t('menuConfig.菜单路径')" min-width="180" />
        <el-table-column :prop="'permission'" :label="t('menuConfig.菜单权限')" min-width="180" />
        <el-table-column :label="t('menuConfig.菜单图标')" width="120">
          <template #default="scope">
            <SvgIcon
              color="#333"
              v-if="scope.row.icon"
              :name="scope.row.icon"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('menuConfig.操作')" width="280">
          <template #default="scope">
            <div class="flex_aic_jcc">
              <div class="operationBtn">
                <el-button
                  type="text"
                  size="small"
                  @click="handleEditMenu(scope.row)"
                  >{{ t('menuConfig.编辑') }}</el-button
                >
              </div>
              <div
                class="operationBtn"
                v-if="scope.row.type === 0 || scope.row.type === 1"
              >
                <el-button
                  type="text"
                  size="small"
                  @click="handleAddSubMenu(scope.row)"
                  >{{ t('menuConfig.添加子菜单') }}</el-button
                >
              </div>
              <el-popconfirm
                :title="t('menuConfig.确定删除吗')"
                @confirm="handleDeleteMenu(scope.row)"
                :confirm-button-text="t('menuConfig.确定')"
                :cancel-button-text="t('menuConfig.取消')"
                width="260px"
              >
                <template #reference>
                  <el-button class="ml0" type="text" size="small"
                    >{{ t('menuConfig.删除') }}</el-button
                  >
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 菜单编辑对话框 -->
    <Dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? t('menuConfig.添加菜单') : t('menuConfig.编辑菜单')"
      width="500px"
      @confirm="submitForm"
      :confirmLoading="confirmLoading"
    >
      <LangTabs v-model="lang" />
      <el-form
        :model="menuForm"
        :rules="rules"
        ref="menuFormRef"
        label-width="120px"
      >
        <el-form-item :label="t('menuConfig.菜单类型')" prop="type">
          <el-select v-model="menuForm.type" :placeholder="t('menuConfig.请选择菜单类型')">
            <el-option :value="0" :label="t('menuConfig.目录')" />
            <el-option :value="1" :label="t('menuConfig.菜单')" />
            <el-option :value="2" :label="t('menuConfig.按钮')" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('menuConfig.菜单名称')" :prop="'title' + lang">
          <el-input
            v-model="menuForm['title' + lang]"
            :placeholder="t('menuConfig.请输入菜单名称')"
          />
        </el-form-item>
        <template v-if="menuForm.type === 2">
          <el-form-item :label="t('menuConfig.接口权限标识')" prop="permission">
            <div class="w-full">
              <el-input
                v-model="menuForm.permission"
                :placeholder="t('menuConfig.请输入接口权限标识')"
                style="width: 100%"
              />
            </div>
          </el-form-item>
          <el-form-item
            label="key"
            prop="path"
            :rules="{ required: true, message: t('menuConfig.请输入key'), trigger: 'blur' }"
          >
            <div class="w-full">
              <el-input
                v-model="menuForm.path"
                :placeholder="t('menuConfig.请输入key')"
                style="width: 100%"
              />
            </div>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item :label="t('menuConfig.菜单路径')" prop="path" v-if="menuForm.type === 1">
            <el-input v-model="menuForm.path" :placeholder="t('menuConfig.请输入菜单路径')" />
          </el-form-item>
          <el-form-item :label="t('menuConfig.菜单图标')" prop="icon">
            <el-input v-model="menuForm.icon" :placeholder="t('menuConfig.请输入图标名称')" />
          </el-form-item>

          <el-form-item :label="t('menuConfig.是否外链')" prop="iFrame">
            <el-switch v-model="menuForm.iFrame" />
          </el-form-item>
          <el-form-item :label="t('menuConfig.排序')" prop="menuSort">
            <el-input-number v-model="menuForm.menuSort" :min="0" :max="999" />
          </el-form-item>
        </template>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";
import LangTabs from "@/components/langTabs.vue";
import { setAttrLangs, getLangs } from "@/i18n/tools";

const { t, locale } = useI18n();
const lang = ref(locale.value);
const loading = ref(false);
const confirmLoading = ref(false);
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const menuList = ref([]);

const menuForm = ref({
  id: "",
  path: "",
  icon: "",
  pid: null,
  menuSort: 0,
  type: 1,
  iFrame: false,
  permission: "",
});

const menuFormRef = ref(null);
const rules = ref({
  path: [{ required: true, message: t('menuConfig.请输入菜单路径'), trigger: "blur" }],
  type: [{ required: true, message: t('menuConfig.请选择菜单类型'), trigger: "change" }],
  permission: [
    { required: true, message: t('menuConfig.请输入接口权限标识'), trigger: "blur" },
  ],
});

setAttrLangs(menuForm.value, "title", "");
setAttrLangs(rules.value, "title", {
  required: true,
  message: t('menuConfig.请输入菜单名称'),
  trigger: "blur",
});

const removeHasChildren = (list) => {
  list.forEach((item) => {
    delete item.hasChildren;
    if (item.children && item.children.length > 0) {
      removeHasChildren(item.children);
    }
  });
};
// 获取菜单树结构
const getMenuTree = async () => {
  try {
    loading.value = true;
    const res = await Api.getMenuTree();
    removeHasChildren(res.data);
    menuList.value = res.data || [];
  } catch (error) {
    console.error(t('menuConfig.获取菜单列表失败'), error);
    ElMessage.error(error.message || t('menuConfig.获取菜单列表失败'));
  } finally {
    loading.value = false;
  }
};

// 添加菜单
const handleAddMenu = () => {
  dialogType.value = "add";
  menuForm.value = {
    id: "",
    path: "",
    icon: "",
    pid: null,
    menuSort: 0,
    type: 1,
    iFrame: false,
    permission: "",
  };
  dialogVisible.value = true;
};

// 添加子菜单
const handleAddSubMenu = (row) => {
  dialogType.value = "add";
  menuForm.value = {
    id: "",
    path: "",
    icon: "",
    pid: row.id,
    menuSort: 0,
    type: 1,
    iFrame: false,
    permission: "",
  };
  dialogVisible.value = true;
};

// 编辑菜单
const handleEditMenu = (row) => {
  dialogType.value = "edit";
  menuForm.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
};

// 删除菜单
const handleDeleteMenu = async (row) => {
  await Api.deleteMenu([row.id]).then((res) => {
    if (res.status === 200) {
      ElMessage.success(t('menuConfig.删除成功'));
      getMenuTree(); // 重新获取列表
    }
  });
};

// 提交表单
const submitForm = () => {
  
  menuFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        confirmLoading.value = true;
        const params = {
          componentName: "",
          menuSort: menuForm.value.menuSort,
          component: "",
          path: menuForm.value.path,
          type: menuForm.value.type,
          permission: menuForm.value.permission,
          icon: menuForm.value.icon,
          cache: true,
          hidden: true,
          pid: menuForm.value.pid || 0,
          iFrame: menuForm.value.iFrame,
          userType: 2,
        };
        if (menuForm.value.pid) {
          params.pid = menuForm.value.pid;
        }
  console.log("menuForm.value===", menuForm.value);

        getLangs().forEach((item) => {
          params["title" + item] = menuForm.value["title" + item];
        });

        let _status = 0;
        if (dialogType.value === "add") {
          // 添加菜单
          const { status } = await Api.addMenu(params);
          if (status === 200) {
            ElMessage.success(t('menuConfig.添加成功'));
            _status = 1;
          }
        } else {
          // 编辑菜单
          params.id = menuForm.value.id;
          const { status } = await Api.updateMenu(params);
          if (status === 200) {
            ElMessage.success(t('menuConfig.更新成功'));
            _status = 1;
          }
        }
        if (_status === 1) {
          dialogVisible.value = false;
          getMenuTree(); // 重新获取列表
        }
      } catch (error) {
        console.error(t('menuConfig.保存菜单失败'), error);
      } finally {
        confirmLoading.value = false;
      }
    }
  });
};

onMounted(() => {
  getMenuTree();
});
</script>

<style lang="scss" scoped>
.menu-config-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .toolbar {
    margin-bottom: 20px;
  }

  .operation-buttons {
    display: flex;
    gap: 10px;
  }

  .mr5 {
    margin-right: 5px;
  }

  .mb20 {
    margin-bottom: 20px;
  }

  .ml10 {
    margin-left: 10px;
  }
}

.icon-option {
  display: flex;
  align-items: center;
}

.addBtn {
  height: 28px;
  margin-left: 10px;
  padding: 0 7px;
  border-radius: 3px;
  background: #fff;
  cursor: pointer;
}

:deep(.cover-table) {
  .el-table__cell {
    text-align: left;
  }
}
</style>
